package job;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.List;

/**
 * job黑白名单
 * @author zhangweilin
 * @date 2022/9/2 11:44
 * @Description:
 */
@Component
public class ElasticJobConfWhitelistHandler {

	private final AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Autowired
	private  ElasticJobConfWhitelistProperties elasticJobConfWhitelistProperties;


	/**
	 * 判断是否满足disable条件
	 * @param className
	 * @return
	 */
	public boolean isDisable(String className) {
		try {
			if (null == className || className.trim().length() == 0) {
				return false;
			}
			//全局开关优先,默认值:false
			boolean isDisableAll = elasticJobConfWhitelistProperties.isDisableAll();
			if (isDisableAll) {
				return true;
			}

			//如果没配置，则全不拦, 此为默认情况
			List<String> includePathPatternList = elasticJobConfWhitelistProperties.getIncludePathPatterns();
			if (null == includePathPatternList || includePathPatternList.isEmpty()) {
				return false;
			}

			for (String includePathPattern : includePathPatternList) {
				//如果能匹配到，则为不禁用
				boolean isMatch = antPathMatcher.match(includePathPattern, className);
				if (isMatch) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			//真要有个啥异常，那就不禁用
			return false;
		}
	}

	/**
	 * 是否存在自定义包含某job，返回true说明是通过配置白名单开启的
	 * @return
	 */
	public boolean isHasCustomInclude() {
		List<String> includePathPatternList = elasticJobConfWhitelistProperties.getIncludePathPatterns();
		//说明是通过配置白名单开启的
		if (null != includePathPatternList && !includePathPatternList.isEmpty()) {
			return true;
		}
		return false;
	}

	public String getIncludeJobNameSuffix() {
		return elasticJobConfWhitelistProperties.getIncludeJobNameSuffix();
	}



}
